package com.jcdd.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jcdd.constant.YjyStore;
import com.jcdd.mapper.GoodsDetailMapper;
import com.jcdd.mapper.QnReqTokenMapper;
import com.jcdd.mapper.UserMapper;
import com.jcdd.mapper.WxUserMapper;
import com.jcdd.object.db.QnReqToken;
import com.jcdd.object.db.User;
import com.jcdd.object.front.*;
import com.jcdd.utils.Qiniu;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    QnReqTokenMapper qnReqTokenMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    WxUserMapper wxUserMapper;

    @Autowired
    GoodsDetailMapper goodsDetailMapper;

    /**
     * 获取自己的个人资料
     *
     * @return 自己的个人资料
     */
    // @SaCheckLogin // 这个注解可以直接判断是否是本人，如果不是，不让进
    // 拦截器已经拦截
    @GetMapping("/info")    // 前端没用Long,js有问题，用的String
    public Result getUserInfo() {
        log.info("toke信息：" + StpUtil.getTokenInfo());
        Object loginId = StpUtil.getLoginId();

        log.info("获取自己的个人资料 loginId : " + loginId.toString());
        if (loginId instanceof String) {
            OwnUserInfoFO ownUserInfo = userMapper.getOwnUserInfo(Long.parseLong((String) loginId));
            return Result.success(ownUserInfo);
        }
        log.error("loginId不为String");
        return Result.error("loginId不为String");
    }

    @GetMapping("/goods")    // 前端没用Long,js有问题，用的String
    public Result getUserGoods() {
        log.info("toke信息：" + StpUtil.getTokenInfo());
        Object loginId = StpUtil.getLoginId();
        long userId = Long.parseLong((String) loginId);
        log.info("获取自己的个人资料 userId : " + userId);
        //获取个人发布的闲置信息
        List<HomeFirstGoodsFO> result  = goodsDetailMapper.getUserGoods(userId);
        return Result.success(result);
    }

    @GetMapping("/delGoods")    // 前端没用Long,js有问题，用的String
    public Result delGoods(String goodsId) {
        log.info("toke信息：" + StpUtil.getTokenInfo());
        Object loginId = StpUtil.getLoginId();
        long userId = Long.parseLong((String) loginId);
        log.info("获取自己的个人资料 userId : " + userId);
        //删除物品信息
        boolean result = goodsDetailMapper.delGoods(userId, goodsId);
        return result?Result.success():Result.error();
    }

    @GetMapping("/info/chatUrl")
    public Result getUserChatUrl() {
        log.info("toke信息：" + StpUtil.getTokenInfo());
        Object loginId = StpUtil.getLoginId();
        long id = Long.parseLong((String) loginId);
        String chatUrl = userMapper.selectChatUrlByUserId(id);
        //
        // log.info("获取自己的个人资料 loginId : " + loginId.toString());
        // if (loginId instanceof String) {
        //     OwnUserInfoFO ownUserInfo = userMapper.getOwnUserInfo(Long.parseLong((String) loginId));
        //     return Result.success(ownUserInfo);
        // }
        // log.error("loginId不为String");
        // return Result.error("loginId不为String");
        return Result.success(chatUrl);
    }

    /**
     * 更换头像
     *
     * @param extension 扩展名 限定为 ['jpg', 'jpeg', 'png'];
     * @return 上传凭证和 key
     */
    @GetMapping("/info/chatUrlToken")
    public Result getChatUrlToken(String extension) {
        Auth auth = Auth.create(YjyStore.qiniuAccessKey, YjyStore.qiniuSecretKey);
        // 凭证有效期 /s
        long ddl = 600L;
        // 生成微信图片 chatUrl key----拼接 chatUrlPreKey为 chatUrl/{用户id}/{当前时间戳}
        String chatUrlPreKey = YjyStore.chatUrlPreKey;
        String userId = (String) StpUtil.getLoginId();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String chatUrlKey = chatUrlPreKey + "/" + userId + "/" + timestamp + "." + extension;
        String upToken = auth.uploadToken(YjyStore.bucket, chatUrlKey, ddl, null, true);
        log.info("生成的微信图片前置token为: \n" + upToken);

        // 存入数据库
        QnReqToken qnReqToken = new QnReqToken();
        qnReqToken.setUserId(Long.parseLong(userId));
        qnReqToken.setReqKey(chatUrlKey);
        qnReqToken.setCreateTime(LocalDateTime.now());
        qnReqTokenMapper.insert(qnReqToken);
        return Result.success(new ChangeAvatarFO(upToken, chatUrlKey));
    }

    @PostMapping("/info/chatUrl")
    @Transactional // 添加事务管理
    public Result setChatUrl(@RequestBody String keyFI) {
        Long userId = Long.parseLong((String) StpUtil.getLoginId());
        log.info("userid为" + userId);
        log.info("keyFI为" + keyFI);
        // key为{"key":"avatar/1796137974318899200/1717332019800.jpg"} ,序列化拿到key
        JSONObject jsonObject = JSONUtil.parseObj(keyFI);
        String key = jsonObject.getStr("key");
        log.info("序列化后的 key ：" + key);
        // 至此拿到 key,创建图片url
        String chatUrl = Qiniu.getImageUrl(key);
        userMapper.setchatUrl(userId,chatUrl);
        return Result.success(chatUrl);
    }



    /**
     * 更换头像
     *
     * @param extension 扩展名 限定为 ['jpg', 'jpeg', 'png'];
     * @return 上传凭证和 key
     */
    @GetMapping("/info/avatar")
    public Result setAvatar(String extension) {
        Auth auth = Auth.create(YjyStore.qiniuAccessKey, YjyStore.qiniuSecretKey);
        // 凭证有效期 /s
        long ddl = 600L;
        // 生成头像key----拼接 avatarPreKey为 avatar/{用户id}/{当前时间戳}
        String avatarPreKey = YjyStore.avatarPreKey;
        String userId = (String) StpUtil.getLoginId();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String avatarKey = avatarPreKey + "/" + userId + "/" + timestamp + "." + extension;
        String upToken = auth.uploadToken(YjyStore.bucket, avatarKey, ddl, null, true);
        log.info("生成的头像token为: \n" + upToken);

        // 存入数据库
        QnReqToken qnReqToken = new QnReqToken();
        qnReqToken.setUserId(Long.parseLong(userId));
        qnReqToken.setReqKey(avatarKey);
        qnReqToken.setCreateTime(LocalDateTime.now());
        qnReqTokenMapper.insert(qnReqToken);
        return Result.success(new ChangeAvatarFO(upToken, avatarKey));
    }

    /**
     * 上传七牛云成功后二次确认，更新头像
     *
     * @param keyFI 前端 post请求体 内容
     * @return 成功通知
     */
    @PostMapping("/info/avatar")
    @Transactional // 添加事务管理
    public Result setAvatar0(@RequestBody String keyFI) {
        Long userId = Long.parseLong((String) StpUtil.getLoginId());
        log.info("userid为" + userId);
        log.info("keyFI为" + keyFI);
        // key为{"key":"avatar/1796137974318899200/1717332019800.jpg"} ,序列化拿到key
        JSONObject jsonObject = JSONUtil.parseObj(keyFI);
        String key = jsonObject.getStr("key");
        log.info("序列化后的 key ：" + key);
        // 至此拿到 key,创建图片url
        String avatarUrl = Qiniu.getImageUrl(key);
        userMapper.setAvatarUrl(userId,avatarUrl);
        return Result.success("头像更新成功！");
    }

    /**
     *  修改昵称
     * @param newNameFI 请求体内容
     * @return 昵称修改成功
     */
    @PostMapping("/info/name")
    public Result setName(@RequestBody String newNameFI){
        Long userId = Long.parseLong((String) StpUtil.getLoginId());
        // key为{"key":"avatar/1796137974318899200/1717332019800.jpg"} ,序列化拿到key
        JSONObject jsonObject = JSONUtil.parseObj(newNameFI);
        String newName = jsonObject.getStr("newName");
        log.info("序列化后的 newName ：" + newName);
        userMapper.setName(userId,newName);
        return Result.success("昵称修改成功！");
    }

    /**
     * 修改邮箱
     * @param newMailFI 请求体内容
     * @return 邮箱修改成功
     */
    @PostMapping("/info/mail")
    public Result setMail(@RequestBody String newMailFI){
        Long userId = Long.parseLong((String) StpUtil.getLoginId());
        // key为{"key":"avatar/1796137974318899200/1717332019800.jpg"} ,序列化拿到key
        JSONObject jsonObject = JSONUtil.parseObj(newMailFI);
        String newMail = jsonObject.getStr("newMail");
        log.info("序列化后的 newMail ：" + newMail);
        userMapper.setMail(userId,newMail);
        return Result.success("邮箱修改成功！");
    }

}
